package com.h819.core.db.examples;

import com.h819.core.db.MyDbUtils;
import org.apache.commons.dbutils.DbUtils;

import java.sql.*;

/**
 * @Title: DbUtilsExample.java
 * @Description: TODO(演示了如何使用DbUtils 类)
 * @author H819
 * @date 2010-3-16
 * @version V1.0
 */

public class DbUtilsExample {
	
	public static void main(String[] args) {

		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/test";
		String user = "test";
		String password = "test";
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;

		try {
			conn = MyDbUtils.getInstanceDefault().getConnection(driver, url, user, password);
			stmt = conn.createStatement();
			stmt
					.executeUpdate("INSERT INTO user (USERNAME, PASSWORDHASH) values ('testUser', '123456')");
			DbUtils.closeQuietly(stmt);
			DbUtils.commitAndCloseQuietly(conn);
		} catch (SQLException ex) {
			DbUtils.printStackTrace(ex);
			DbUtils.rollbackAndCloseQuietly(conn);
		}

		PreparedStatement psmt = null;
		try {
			conn = MyDbUtils.getInstanceDefault().getConnection(driver, url, user, password);
			psmt = conn
					.prepareStatement("SELECT USERNAME, PASSWORDHASH FROM user");
			rs = psmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getString(1) + "\t" + rs.getString(2));
			}
		} catch (SQLException ex) {
			DbUtils.printStackTrace(ex);
		} finally {
			DbUtils.closeQuietly(conn, psmt, rs);
		}

		try {
			conn = MyDbUtils.getInstanceDefault().getConnection(driver, url, user, password);
			stmt = conn.createStatement();
			stmt.executeUpdate("DELETE FROM user WHERE USERNAME='testUser'");
			DbUtils.closeQuietly(stmt);
		} catch (SQLException ex) {
			DbUtils.printStackTrace(ex);
		} finally {
			DbUtils.printWarnings(conn);
			DbUtils.closeQuietly(conn);
		}
	}
}
